import java.awt.image.BufferedImage
import java.awt.Graphics
import java.awt.Image

includeTargets << grailsScript("Init")

target(renderAssets: "Renders blender assets into images") {
	def blenderExe = 'C:\\apps\\blender\\blender.exe';
	def asset_dir = 'C:\\git\\grails-js-mud\\app-assets';
	def target = 'web-app\\images\\';
	
	def BLENDER_EXTENTION = ~/.*\.blend$/
	def PATH_SEP = File.separator
	
	def root = new File("${asset_dir}");
	def targetDir = new File("${target}");	
	
	println( "Rendering...")
	root.eachFileRecurse(){
		file ->
				
		if( !(file.name =~ BLENDER_EXTENTION ) ) return;
				
		def asset = file.parent[root.path.length()+1..-1] + PATH_SEP + file.name[0..-7]
		def assetName = asset.substring( asset.lastIndexOf(PATH_SEP)+1 )
		def assetPath = asset[0..(-1*assetName.length() -1)]
		assetPath = assetPath[assetPath.indexOf(PATH_SEP)..-1]
		def output = targetDir.absolutePath + assetPath + assetName
				
		def lastModified = 0
		
		if( targetDir.exists() ){
			def outputDir = new File(targetDir, assetPath)
			def files = outputDir.listFiles({ pdir, pname -> pname ==~ "${assetName}.*" } as FilenameFilter) 
			if( files != null && files.length > 0) lastModified = files[0].lastModified()
		}
		if( file.lastModified() < lastModified ){ 
			println("[no-change] ${output}") 
			return
		}
		def pythonScript = "render.py"
		
		def run = {
			name ->
			command = [blenderExe, "--background", file, "--render-output", "${output}","--python", pythonScript]

            println command
			def proc = command.execute()
			proc.consumeProcessOutput()
			proc.waitFor()
			if( proc.exitValue() )
			   println proc.err.text;
			else
			   println proc.in.text;
			//proc.consumeProcessOutput()
			//def blah = proc.in.text
			//def error = proc.err.text
			//println blah
			//if( error ){
			//	println "FAILED ###\n${error}"
			//}
		}
		println( "[rendering] ${output}")
		if( assetName =~ /circle_*./) pythonScript = "circle_render.py";
		run( output )
	};
}

setDefaultTarget(renderAssets)
